#include "transcodeprogressdialog.h"
#include <QDebug>

/**
 * @brief 构造函数
 */
TranscodeProgressDialog::TranscodeProgressDialog(const QString &fileName, QWidget *parent)
    : QDialog(parent)
    , m_titleLabel(nullptr)
    , m_fileLabel(nullptr)
    , m_statusLabel(nullptr)
    , m_progressBar(nullptr)
    , m_progressLabel(nullptr)
    , m_timeLabel(nullptr)
    , m_cancelButton(nullptr)
    , m_updateTimer(nullptr)
    , m_currentProgress(0)
    , m_timerStarted(false)
{
    setupUI(fileName);
    
    // 创建更新定时器
    m_updateTimer = new QTimer(this);
    connect(m_updateTimer, &QTimer::timeout, this, &TranscodeProgressDialog::onUpdateTimeEstimate);
}

/**
 * @brief 析构函数
 */
TranscodeProgressDialog::~TranscodeProgressDialog()
{
    if (m_updateTimer) {
        m_updateTimer->stop();
    }
}

/**
 * @brief 初始化UI
 */
void TranscodeProgressDialog::setupUI(const QString &fileName)
{
    setWindowTitle("视频优化中");
    setFixedSize(500, 300);
    setModal(true);  // 模态对话框
    
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(30, 30, 30, 30);
    mainLayout->setSpacing(20);
    
    // 标题标签
    m_titleLabel = new QLabel("视频需要优化才能播放", this);
    m_titleLabel->setAlignment(Qt::AlignCenter);
    m_titleLabel->setStyleSheet(
        "QLabel { font-size: 16px; font-weight: bold; color: #2c3e50; }"
    );
    mainLayout->addWidget(m_titleLabel);
    
    // 文件名标签
    m_fileLabel = new QLabel(fileName, this);
    m_fileLabel->setAlignment(Qt::AlignCenter);
    m_fileLabel->setWordWrap(true);
    m_fileLabel->setStyleSheet(
        "QLabel { font-size: 13px; color: #34495e; padding: 5px; }"
    );
    mainLayout->addWidget(m_fileLabel);
    
    // 状态标签
    m_statusLabel = new QLabel("正在优化视频格式...", this);
    m_statusLabel->setAlignment(Qt::AlignCenter);
    m_statusLabel->setStyleSheet(
        "QLabel { font-size: 12px; color: #7f8c8d; }"
    );
    mainLayout->addWidget(m_statusLabel);
    
    mainLayout->addSpacing(10);
    
    // 进度条
    m_progressBar = new QProgressBar(this);
    m_progressBar->setRange(0, 100);
    m_progressBar->setValue(0);
    m_progressBar->setTextVisible(false);
    m_progressBar->setFixedHeight(25);
    m_progressBar->setStyleSheet(
        "QProgressBar { "
        "  border: 2px solid #bdc3c7; "
        "  border-radius: 5px; "
        "  background-color: #ecf0f1; "
        "  text-align: center; "
        "} "
        "QProgressBar::chunk { "
        "  background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, "
        "    stop:0 #3498db, stop:1 #2980b9); "
        "  border-radius: 3px; "
        "}"
    );
    mainLayout->addWidget(m_progressBar);
    
    // 进度百分比标签
    m_progressLabel = new QLabel("0%", this);
    m_progressLabel->setAlignment(Qt::AlignCenter);
    m_progressLabel->setStyleSheet(
        "QLabel { font-size: 18px; font-weight: bold; color: #3498db; }"
    );
    mainLayout->addWidget(m_progressLabel);
    
    // 剩余时间标签
    m_timeLabel = new QLabel("预计剩余时间: 计算中...", this);
    m_timeLabel->setAlignment(Qt::AlignCenter);
    m_timeLabel->setStyleSheet(
        "QLabel { font-size: 11px; color: #95a5a6; }"
    );
    mainLayout->addWidget(m_timeLabel);
    
    mainLayout->addStretch();
    
    // 取消按钮
    m_cancelButton = new QPushButton("取消添加", this);
    m_cancelButton->setFixedSize(150, 45);
    m_cancelButton->setStyleSheet(
        "QPushButton { "
        "  background-color: #e74c3c; "
        "  color: white; "
        "  border: none; "
        "  border-radius: 5px; "
        "  font-size: 13px; "
        "  font-weight: bold; "
        "} "
        "QPushButton:hover { "
        "  background-color: #c0392b; "
        "} "
        "QPushButton:pressed { "
        "  background-color: #a93226; "
        "}"
    );
    
    // 按钮居中布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_cancelButton);
    buttonLayout->addStretch();
    mainLayout->addLayout(buttonLayout);
    
    // 连接信号
    connect(m_cancelButton, &QPushButton::clicked, this, &TranscodeProgressDialog::onCancelClicked);
    
    // 设置对话框样式
    setStyleSheet(
        "QDialog { "
        "  background-color: #ecf0f1; "
        "  border: 2px solid #bdc3c7; "
        "  border-radius: 10px; "
        "}"
    );
}

/**
 * @brief 更新进度
 */
void TranscodeProgressDialog::updateProgress(int progress)
{
    m_currentProgress = progress;
    m_progressBar->setValue(progress);
    m_progressLabel->setText(QString("%1%").arg(progress));
    
    // 启动计时器（首次进度更新时）
    if (!m_timerStarted && progress > 0) {
        startTimer();
    }
    
    // 更新剩余时间
    if (m_timerStarted && progress > 0 && progress < 100) {
        QString remaining = calculateRemainingTime(progress);
        m_timeLabel->setText(QString("预计剩余时间: %1").arg(remaining));
    }
    
    // 完成时更新状态
    if (progress >= 100) {
        m_statusLabel->setText("优化完成！");
        m_timeLabel->setText("转码已完成");
        m_cancelButton->setEnabled(false);
        
        if (m_updateTimer) {
            m_updateTimer->stop();
        }
    }
}

/**
 * @brief 设置状态文本
 */
void TranscodeProgressDialog::setStatusText(const QString &text)
{
    m_statusLabel->setText(text);
}

/**
 * @brief 启动计时器
 */
void TranscodeProgressDialog::startTimer()
{
    if (!m_timerStarted) {
        m_startTime = QTime::currentTime();
        m_timerStarted = true;
        
        // 每秒更新一次剩余时间
        m_updateTimer->start(1000);
        
        qDebug() << "Transcode timer started";
    }
}

/**
 * @brief 取消按钮点击
 */
void TranscodeProgressDialog::onCancelClicked()
{
    qDebug() << "User requested to cancel transcode";
    
    // 发送取消信号
    emit cancelRequested();
    
    // 关闭对话框
    reject();
}

/**
 * @brief 更新剩余时间显示
 */
void TranscodeProgressDialog::onUpdateTimeEstimate()
{
    if (m_currentProgress > 0 && m_currentProgress < 100) {
        QString remaining = calculateRemainingTime(m_currentProgress);
        m_timeLabel->setText(QString("预计剩余时间: %1").arg(remaining));
    }
}

/**
 * @brief 计算剩余时间
 */
QString TranscodeProgressDialog::calculateRemainingTime(int progress)
{
    if (!m_timerStarted || progress <= 0) {
        return "计算中...";
    }
    
    // 计算已用时间（秒）
    int elapsedSeconds = m_startTime.secsTo(QTime::currentTime());
    
    if (elapsedSeconds <= 0) {
        return "计算中...";
    }
    
    // 计算总时间 = 已用时间 / 当前进度
    double totalSeconds = elapsedSeconds * 100.0 / progress;
    
    // 计算剩余时间
    int remainingSeconds = static_cast<int>(totalSeconds - elapsedSeconds);
    
    if (remainingSeconds < 0) {
        remainingSeconds = 0;
    }
    
    return formatTime(remainingSeconds);
}

/**
 * @brief 格式化时间显示
 */
QString TranscodeProgressDialog::formatTime(int seconds)
{
    if (seconds < 60) {
        return QString("%1秒").arg(seconds);
    } else if (seconds < 3600) {
        int minutes = seconds / 60;
        int secs = seconds % 60;
        return QString("%1分%2秒").arg(minutes).arg(secs);
    } else {
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        return QString("%1小时%2分").arg(hours).arg(minutes);
    }
}

